const express = require('express')
const bcrypt = require('bcrypt')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const db = require('../../db')
const key = require('../../config/key')
const router = express.Router()
const expressJoi = require('@escook/express-joi')
const {users_register_schema, users_login_schema} = require('../../schema/users')
const passport = require('passport')

router.get('/test', (req, res) => {
    const sqlStr = 'select * from users'
    db.query(sqlStr, (err, results) => {
        if(err) return res.json({msg: 'sql语句执行失败'})
        res.json(results)
    })
})

router.post('/register', expressJoi(users_register_schema),(req, res) => {
    const sqlStr = 'select * from users where email = ?'
    db.query(sqlStr, req.body.email, (err, results) => {
        if(err) return res.json({status: 1,message: 'sql语句执行失败'})
        if(results.length > 0) return res.json({ status: 1, message: '邮箱被占用，请更换其他邮箱！' })
        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(req.body.password, salt, function(err, hash) {
                if(err) throw err
                req.body.password = hash
                req.body.avatar = 'https://cravatar.cn/avatar/' + md5(req.body.email)
                const sql = 'insert into users set ?'
                db.query(sql, req.body, (err, results) => {
                    if(err) return res.json({status: 1,message: 'sql语句执行失败'})
                    if(results.affectedRows !== 1) return res.json({ status: 1, message: '注册失败' })
                    res.json({ status: 0, message: '注册成功'})
                })
            });
        });

    })
})

router.post('/login', expressJoi(users_login_schema),(req, res) => {
    const {email, password} = req.body
    const sqlStr = 'select * from users where email = ?'
    db.query(sqlStr, email, (err, results) => {
        if(err) return res.json({status: 1,message: 'sql语句执行失败'})
        if(results.length === 0) return res.json({status: 1, message: '邮箱未注册'})
        bcrypt.compare(password, results[0].password, function(err, result) {
            if(err) throw err
            if(result){
                const rule = {id: results[0].id, name: results[0].name, email: results[0].email, avatar: results[0].avatar, role: results[0].role}
                const token = jwt.sign(rule, key.serectOrKey, {expiresIn: '3h'})
                return res.json({
                    status: 0,
                    message: '登录成功',
                    token: 'Bearer ' + token
                })
            }
            res.json({status:1, message: '密码错误'})
        });
    })
})

router.get('/current',passport.authenticate('jwt', {session: false}), (req, res) => {
    res.json(req.user)
})

module.exports = router